'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const DailyPlan = require('./daily_plan');

const DailyPlanItem = sequelize.define(
  'DailyPlanItem',
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      primaryKey: true,
      autoIncrement: true,
      comment: '每日计划行程项ID',
    },
    daily_plan_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      comment: '所属每日计划ID',
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '地点名称',
    },
    type: {
      type: DataTypes.STRING(20),
      allowNull: false,
      defaultValue: 'custom',
      comment: '地点类型: attraction/custom',
    },
    time: {
      type: DataTypes.STRING(10),
      allowNull: true,
      comment: '计划时间，格式HH:mm',
    },
    note: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '备注',
    },
    order_index: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      defaultValue: 0,
      comment: '展示顺序',
    },
  },
  {
    tableName: 'daily_plan_items',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    underscored: true,
  }
);

// 关联：行程项 属于 每日计划；每日计划 拥有 多个行程项
DailyPlanItem.belongsTo(DailyPlan, { foreignKey: 'daily_plan_id', as: 'dailyPlan', onDelete: 'CASCADE' });
DailyPlan.hasMany(DailyPlanItem, { foreignKey: 'daily_plan_id', as: 'items', onDelete: 'CASCADE' });

// 初始化表与开发环境种子数据
(async () => {
  try {
    // await DailyPlanItem.sync({ alter: true });

    // 仅在开发环境且当前表无数据时插入示例行程项
    if (process.env.NODE_ENV !== 'production') {
      const count = await DailyPlanItem.count();
      if (count === 0) {
        const days = await DailyPlan.findAll({ order: [['plan_id', 'ASC'], ['day', 'ASC']], limit: 2 });
        if (Array.isArray(days) && days.length > 0) {
          const payloads = [];
          if (days[0]) {
            const d1 = days[0];
            payloads.push(
              { daily_plan_id: d1.id, name: '机场到酒店', type: 'custom', time: '10:00', note: '办理入住', order_index: 0 },
              { daily_plan_id: d1.id, name: '浅草寺', type: 'attraction', time: '14:00', note: '参观', order_index: 1 },
              { daily_plan_id: d1.id, name: '晴空塔', type: 'attraction', time: '17:00', note: '拍照打卡', order_index: 2 },
            );
          }
          if (days[1]) {
            const d2 = days[1];
            payloads.push(
              { daily_plan_id: d2.id, name: '上野公园', type: 'attraction', time: '09:30', note: '晨间散步', order_index: 0 },
              { daily_plan_id: d2.id, name: '东京塔', type: 'attraction', time: '15:00', note: '俯瞰城市', order_index: 1 },
              { daily_plan_id: d2.id, name: '银座购物', type: 'custom', time: '18:00', note: '自由活动', order_index: 2 },
            );
          }
          if (payloads.length > 0) {
            await DailyPlanItem.bulkCreate(payloads);
            console.log('✅ 已插入示例每日计划行程项数据');
          }
        }
      }
    }
  } catch (e) {
    console.error('DailyPlanItem 模型初始化失败:', e);
  }
})();

module.exports = DailyPlanItem;